package web

import (
	"encoding/base32"
	"encoding/json"
	"io"
	"net/http"
	"time"

	"github.com/gorilla/securecookie"
	"github.com/sirupsen/logrus"
	"github.com/wi-cuckoo/eastlake/schedule"
	"github.com/wi-cuckoo/eastlake/server"
	"github.com/wi-cuckoo/eastlake/util"
	"github.com/wi-cuckoo/eastlake/web/model"
	"github.com/wi-cuckoo/eastlake/web/service"
)

func (s *Server) handlePing() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		logrus.Debug("ping")
		io.WriteString(w, "ok")
	}
}

func (s *Server) demo(w http.ResponseWriter, r *http.Request) {
	schedule.Enqueue(server.TestStage.ID)
}

func (s *Server) homePage() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		logrus.Debug("home page")
		io.WriteString(w, "<h1>home page</h1>")
	}
}

func (s *Server) login() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		user, err := service.Gitlab.Login(w, r)
		if err == nil {
			logrus.Infof("user: %v\n", user)
		} else {
			logrus.Errorf("err: %v\n", err)
			io.WriteString(w, "<h1>login failed</h1>")
			return
		}
		var u *model.User
		// get the user from the database
		u, err = service.Orm.UserInfo(user.UID)
		if err != nil {
			logrus.Errorf("err: %v\n", err)
		}
		if u.UID == 0 {
			// create the user account
			u = &model.User{
				UID:      user.UID,
				GID:      user.GID,
				Username: user.Username,
				Nickname: user.Nickname,
				Token:    user.Token,
				Secret:   user.Secret,
				Email:    user.Email,
				Avatar:   user.Avatar,
				Hash: base32.StdEncoding.EncodeToString(
					securecookie.GenerateRandomKey(32),
				),
				CreateTime: time.Now().Unix(),
				UpdateTime: time.Now().Unix(),
			}
			service.Orm.CreateUser(u)

		} else {
			// update the user account
			u.UpdateTime = time.Now().Unix()
			service.Orm.UpdateUser(u.UID, u)
		}

		util.SetCookie(w, r, "username", user.Username)
		http.Redirect(w, r, "/", http.StatusFound)

	}
}

func (s *Server) logout() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// just clear the cookie
		util.DelCookie(w, r, "username")
		io.WriteString(w, "you have logout successfully!")
	}
}

func (s *Server) UserInfo() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		username := util.GetCookie(r, "username")
		u, err := service.Orm.UserInfoByUsername(username)
		if err != nil {
			logrus.Errorf("err: %v\n", err)
			io.WriteString(w, "<h1>login failed</h1>")
			return
		}
		json.NewEncoder(w).Encode(u)
	}
}
